package com.diamondsys.embrapa.util;

import java.security.MessageDigest;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
 
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import org.apache.commons.codec.binary.Base64;

 
public class RetrieveUserAttributes {

    public LdapContext getLdapContext(){
        LdapContext ctx = null;
        try{
            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.SECURITY_AUTHENTICATION, "none");
            env.put(Context.SECURITY_PRINCIPAL, "cn=Manager,ou=People,dc=cnpso,dc=embrapa,dc=br");
            env.put(Context.PROVIDER_URL, "ldap://dourado.cnpso.embrapa.br:389/dc=cnpso,dc=embrapa,dc=br");
            ctx = new InitialLdapContext(env, null);
            System.out.println("Conexão efetuada com sucesso");
        }catch(NamingException nex){
            System.out.println("LDAP Conexão: falha");
            nex.printStackTrace();
        }
        return ctx;
    }
 
    public Boolean conectarSenha(String nome, String senha){
        
        try{
            LdapContext ctx = this.getLdapContext();
            

            Hashtable<String, String> environment = (Hashtable<String, String>)ctx.getEnvironment().clone();
            environment.put(Context.SECURITY_AUTHENTICATION, "simple");
            environment.put(Context.SECURITY_PRINCIPAL,  String.format("uid=%s,ou=People,dc=cnpso,dc=embrapa,dc=br",nome));
            environment.put(Context.SECURITY_CREDENTIALS, senha);

            DirContext dirContext = new InitialDirContext(environment);            
            System.out.println(dirContext.toString());
            return true;
        }catch(NamingException nex){
            System.out.println("LDAP Connection: FAILED");
            nex.printStackTrace();
        }
        return false;
    }
    
    public Boolean getUserBasicAttributes(String username, String password ) {

        String result = "";
        
        try {
            LdapContext ctx = this.getLdapContext();
            SearchControls constraints = new SearchControls();
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration results = ctx.search("", String.format("(uid=%s)",username) , constraints);
            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();            
                Attributes attributes = searchResult.getAttributes();  

                if(attributes.get("sambaPwdLastSet")!=null) result += "\n " + ("sambaPwdLastSet: " + attributes.get("sambaPwdLastSet").get()); 
                if(attributes.get("givenName")!=null) result += "\n " + ("givenName: " + attributes.get("givenName").get()); 
                if(attributes.get("sn")!=null) result += "\n " + ("sn: " + attributes.get("sn").get()); 
                if(attributes.get("loginShell")!=null) result += "\n " + ("loginShell: " + attributes.get("loginShell").get()); 
                if(attributes.get("sambaAcctFlags")!=null) result += "\n " + ("sambaAcctFlags: " + attributes.get("sambaAcctFlags").get()); 
                if(attributes.get("gidNumber")!=null) result += "\n " + ("gidNumber: " + attributes.get("gidNumber").get()); 
                if(attributes.get("uidNumber")!=null) result += "\n " + ("uidNumber: " + attributes.get("uidNumber").get()); 
                if(attributes.get("mail")!=null) result += "\n " + ("mail: " + attributes.get("mail").get()); 
                if(attributes.get("uid")!=null) result += "\n " + ("uid: " + attributes.get("uid").get()); 
                if(attributes.get("objectClass")!=null) result += "\n " + ("objectClass: " + attributes.get("objectClass").get()); 
                if(attributes.get("sambaDomainName")!=null) result += "\n " + ("sambaDomainName: " + attributes.get("sambaDomainName").get()); 
                if(attributes.get("sambaSID")!=null) result += "\n " + ("sambaSID: " + attributes.get("sambaSID").get()); 
                if(attributes.get("sambaHomeDrive")!=null) result += "\n " + ("sambaHomeDrive: " + attributes.get("sambaHomeDrive").get()); 
                if(attributes.get("cn")!=null) result += "\n " + ("cn: " + attributes.get("cn").get()); 
                if(attributes.get("homeDirectory")!=null) result += "\n " + ("homeDirectory: " + attributes.get("homeDirectory").get()); 
                if(attributes.get("sambaPrimaryGroupSID")!=null) result += "\n " + ("sambaPrimaryGroupSID: " + attributes.get("sambaPrimaryGroupSID").get()); 
                if(attributes.get("sambaNTPassword")!=null) result += "\n " + ("sambaNTPassword: " + attributes.get("sambaNTPassword").get()); 
                result += "\n " + ("generated pass: " + hashMD5Password(password)); 
                System.out.println(result);
                return true;
            }  
        }
        catch(NamingException ex){ex.printStackTrace();}
        
        return false;
    }
    
    public static String hashMD5Password(String password) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
            digest.update(password.getBytes("UTF8"));
            String md5Password = Base64.encodeBase64String(digest.digest());
            return "{MD5}" + md5Password;
        } catch (Exception  ex) {
            Logger.getLogger(RetrieveUserAttributes.class.getName()).log(Level.SEVERE, null, ex);
        }

        return "";

    }    
}

